<template>
  <div class="app-container">

    <div class="flex jc-between">
      <YxhyTableQuery :query-params.sync="queryParams" :query-columns="queryColumns" @search="handleQuery">
        <template slot="selectRemote" slot-scope="{param}">
          <template v-if="param === 'dist_id'">
            <YxhySelectRemote
              :value.sync="queryParams.dist_id"
              :filterable="false"
              :request-fn="queryDistUserAll"
              :request-key="`company`"
              :response-id="`id`"
              :response-name="`company`"
              :placeholder="`请选择分销商`"
            />
          </template>
          <template v-if="param === 'seed_id'">
            <YxhySelectRemote
              ref="yxhySelectRemoteSeedId"
              :value.sync="queryParams.seed_id"
              :shouldCreatInit="false"
              :filterable="false"
              :request-fn="queryDistUserList"
              :request-other="{
                pageNum: 1,
                limit: 10000,
                p_id: queryParams.dist_id
              }"
              :request-key="`chinese_name`"
              :response-id="`id`"
              :response-name="`chinese_name`"
              :placeholder="`请选择投手`"
            />
          </template>
          <template v-if="param === 'admin_id'">
            <YxhySelectRemote
              :value.sync="queryParams.admin_id"
              :filterable="false"
              :request-fn="queryUserAllList"
              :request-key="`name_search`"
              :response-id="`id`"
              :response-name="`chinese_name`"
              :placeholder="`请选择操作人`"
            />
          </template>
        </template>
        <template #datetimeRange>
          <YxhyDatetimeRange
            :start-date.sync="queryParams.start_date"
            :end-date.sync="queryParams.end_date"
            :start-placeholder="`开始日期`"
            :end-placeholder="`结束日期`"
          />
        </template>
        <el-form-item slot="button">
          <el-button v-hasPermi="['statistics:channeled:export']" type="success" @click="handleExport">导出</el-button>
        </el-form-item>
      </YxhyTableQuery>
    </div>

    <YxhyTableData
      :columns="columns"
      :data="tableList"
      :loading="loading"
      :stripe="false"
    >
      <!-- 消耗金额插槽 -->
      <template #consume_money>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <div class="flex jc-center">
              <p class="font-color-th">消耗金额</p>
              <SortIcon :query-params.sync="queryParams" this-key="cost" @refresh="init" />
            </div>
            <p class="font-color-th">当日ROI</p>
          </template>
          <template slot-scope="{ row }">
            <p class="font-color-td">￥{{ row.cost }}</p>
            <p class="font-color-td">{{ row.roi }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 充值金额插槽 -->
      <template #number_of_people>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <div class="flex jc-center">
              <p class="font-color-th">充值金额</p>
              <SortIcon :query-params.sync="queryParams" this-key="recharge_amount" @refresh="init" />
            </div>
            <p class="font-color-th">充值人数</p>
          </template>
          <template slot-scope="{ row }">
            <p class="font-color-td">￥{{ row.recharge_amount }}</p>
            <p class="font-color-td">{{ row.recharge_number }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 新增充值金额插槽 -->
      <template #add_number_of_money>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">新增充值金额</p>
            <p class="font-color-th">新增充值人数</p>
          </template>
          <template slot-scope="{ row }">
            <p class="font-color-td">￥{{ row.n_recharge_amount }}</p>
            <p class="font-color-td">{{ row.n_recharge_number }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 当日复充人数插槽 -->
      <template #repeat_people>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">当日复充人数</p>
            <p class="font-color-th">当日复充率</p>
          </template>
          <template slot-scope="{ row }">
            <p class="font-color-td">{{ row.f_recharge_number }}</p>
            <p class="font-color-td">{{ row.f_recharge_rate }}%</p>
          </template>
        </el-table-column>
      </template>
    </YxhyTableData>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryPage.pageNum"
      :limit.sync="queryPage.limit"
      @pagination="init"
    />

  </div>
</template>

<script>
import { columnsStatic } from './Ds.js'
import { queryNonSortLibrary } from '@/api/video/library'
import { queryChannelDailyStatistics } from '@/api/statistics/channeled'
import SortIcon from '@/components/SortIcon/index.vue'
import { queryDistUserAll, queryDistUserList } from '@/api/distribute/distAccount'
import { queryUserAllList } from '@/api/system/account'

export default {
  name: 'ChanneledList',
  components: { SortIcon },
  data() {
    return {
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 分页参数
      queryPage: {
        pageNum: 1,
        limit: 10
      },
      // 查询参数
      queryParams: {
        cid: undefined,
        name: undefined,
        start_date: undefined,
        end_date: undefined,
        dist_id: undefined,
        seed_id: undefined,
        admin_id: undefined
      },
      // 查询表单
      queryColumns: [
        {
          label: '',
          placeholder: '请输入渠道ID',
          type: 'input',
          param: 'cid'
        },
        {
          label: '',
          placeholder: '请输入渠道名称',
          type: 'input',
          param: 'name'
        },
        {
          type: 'datetimeRange',
          param: 'datetime_search'
        },
        {
          label: '',
          placeholder: '请选择分销商',
          type: 'selectRemote',
          param: 'dist_id'
        },
        {
          label: '',
          placeholder: '请选择投手',
          type: 'selectRemote',
          param: 'seed_id'
        },
        {
          label: '',
          placeholder: '请选择操作人',
          type: 'selectRemote',
          param: 'admin_id'
        }
      ],

      loading: false,
      // 表格列
      columns: columnsStatic,

      queryNonSortLibrary,
      queryDistUserAll,
      queryDistUserList,
      queryUserAllList
    }
  },
  computed: {
    isCopyright() {
      return this.$store.state.user.roles.includes('copyright')
    }
  },
  watch: {
    'queryParams.dist_id': {
      handler(val) {
        if (!val) {
          this.queryParams.seed_id = undefined
          this.$refs.yxhySelectRemoteSeedId.reset()
        } else {
          this.$nextTick(() => {
            this.$refs.yxhySelectRemoteSeedId.remoteMethod()
          })
        }
      },
      deep: true,
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      const res = await queryChannelDailyStatistics({
        ...this.queryPage,
        ...this.queryParams
      })
      res.data.forEach(e => {
        const { f_recharge_rate, registered_num, company, channel_pitcher } = e
        e.company = company || '-'
        e.channel_pitcher = channel_pitcher || '-'
        e.registered_num = registered_num || '-'
        if (f_recharge_rate === 0) {
          e.f_recharge_rate = 0
        } else {
          e.f_recharge_rate = this.reserveNumberZero(f_recharge_rate)
        }
      })
      this.tableList = res.data
      this.total = res.total
      this.loading = false
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        type: 1,
        oss_id: undefined
      }
      this.resetForm('formRef')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryPage.pageNum = 1
      this.init()
    },
    /** 导出按钮 */
    async handleExport() {
      this.download(
        `/channel/daily/statistics/export?page=${this.queryPage.pageNum}`,
        {
          ...this.queryPage,
          ...this.queryParams
        },
        `data_${new Date().getTime()}.xlsx`
      )
    },

    calculateTd(arr) {
      const result = arr.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) return prev + curr
        else return prev
      }, 0)
      return result
    },

    // 保留两位小数，不四舍五入
    reserveNumberTow(number) {
      return Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(number)
    },
    // 百分比，不保留小数
    reserveNumberZero(number) {
      return Intl.NumberFormat('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(number)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
